<?php

class Utils
{

  // funcion para castear objetos
  static public function cast($object, $class)
  {
    if (!is_object($object))
      throw new InvalidArgumentException('$object must be an object.');
    if (!is_string($class))
      throw new InvalidArgumentException('$class must be a string.');
    if (!class_exists($class))
      throw new InvalidArgumentException(sprintf('Unknown class: %s.', $class));
    if (!is_subclass_of($class, get_class($object)))
      throw new InvalidArgumentException(sprintf(
          '%s is not a descendant of $object class: %s.', $class, get_class($object)
      ));

    /**
     * This is a beautifully ugly hack.
     *
     * First, we serialize our object, which turns it into a string, allowing
     * us to muck about with it using standard string manipulation methods.
     *
     * Then, we use preg_replace to change it's defined type to the class
     * we're casting it to, and then serialize the string back into an
     * object.
     */
    return unserialize(
        preg_replace(
          '/^O:\d+:"[^"]++"/', 'O:' . strlen($class) . ':"' . $class . '"', serialize($object)
        )
    );

  }

  function my_convert_encoding($string, $to, $from)
  {
    // Convert string to ISO_8859-1
    if ($from == "UTF-8")
      $iso_string = utf8_decode($string);
    else
    if ($from == "UTF7-IMAP")
      $iso_string = imap_utf7_decode($string);
    else
      $iso_string = $string;

    // Convert ISO_8859-1 string to result coding
    if ($to == "UTF-8")
      return(utf8_encode($iso_string));
    else
    if ($to == "UTF7-IMAP")
      return(imap_utf7_encode($iso_string));
    else
      return($iso_string);

  }

}

